package com.lemon.cloud.security.model;

import com.google.common.collect.Lists;
import com.lemon.cloud.comm.constants.enums.UserTypeEnum;
import com.lemon.cloud.comm.po.SocialUser;
import com.lemon.cloud.comm.po.SysOrg;
import com.lemon.cloud.comm.po.SysUser;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 授权用户
 */
public class SecurityUser extends User implements OAuth2AuthenticatedPrincipal {
    private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
    /**
     * 管理员用户
     */
    @Getter
    @Setter
    private SysUser sysUser;

    /**
     * c端用户
     */
    @Getter
    @Setter
    private SocialUser socialUser;

    @Getter
    @Setter
    private UserTypeEnum userTypeEnum;

    private final Map<String, Object> attributes = new HashMap<>();


    public SecurityUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, authorities);
    }

    /**
     * 账户是否未过期
     * @return
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 账户是否未被锁
     * @return
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    @Override
    public Map<String, Object> getAttributes() {
        return this.attributes;
    }

    /**
     * 游客用户
     * @return
     */
    public static SecurityUser getVisitor(){
        return new SecurityUser(null,null, AuthorityUtils.NO_AUTHORITIES);
    }

    @Override
    public String getName() {
        return this.getUsername();
    }

    public Long getId() {
        switch (userTypeEnum){
            case SYS_USER:return this.sysUser.getId();
            case SOCIAL_USER:return this.socialUser.getUserId();
            default:break;
        }
        return null;
    }

    public List<Long> getOrgIds() {
        switch (userTypeEnum){
            case SYS_USER:return this.sysUser.getOrgList().stream().map(SysOrg::getId).collect(Collectors.toList());
            case SOCIAL_USER:return Lists.newArrayList();
            default:break;
        }
        return Lists.newArrayList();
    }
}
